
import axios from 'axios'
import { ElMessage } from 'element-plus';
import Qs from 'qs'
import router from '../router'
import store from '../store'


axios.defaults.baseURL = 'https://wjapi.surveydiscovery.com/api/'

axios.defaults.withCredentials = false

// 从store获取token，如果没有则从localStorage获取
const getAuthToken = () => {
    const storeToken = store?.state?.token
    if (storeToken) {
        return storeToken
    }
    return localStorage.getItem("token")
}

const getuid = () => {
    return localStorage.getItem("uid")
}

axios.defaults.headers['Authorization'] = "Bearer " + getuid() + "." + getAuthToken() + '.2'
axios.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded; charset=UTF-8'
axios.interceptors.response.use(res => {
    if(res?.config?.url.indexOf('login/login')!==-1){
        // 判断token是否过去，是重新更新token
        const token = res.data?.data?.token
        const uid = res.data?.data?.uid
        
        if (token) {
            localStorage.setItem('token', token)
            // 同时更新store中的token
            store.commit('setToken', token)
        }
        
        if (uid) {
            localStorage.setItem('uid', uid)
        }
        
        // 更新axios默认headers
        axios.defaults.headers['Authorization'] = "Bearer " + uid + "." + token + '.2'
    }
    return new Promise((resolve,reject)=>{
        if(res.data.code === 10000){
            resolve(res.data)
        }else if(res.data.code === 305){
            resolve(res.data)
        }else if(res.data.code === 300){
            ElMessage.error({
                message: res.data.message,
                offset: 100,
                duration: 5000
            })
            reject(new Error(res.data.message || '请求失败'))
        }else if(res.data.code === 301){
            ElMessage.error({
                message: res.data.message,
                offset: 100,
                duration: 5000
            })
            router.push('/login')
            reject(new Error(res.data.message || '认证失败'))
        }else if(res.data.code === 303){
            ElMessage.error({
                message: res.data.message,
                offset: 100,
                duration: 5000
            })
            reject(new Error(res.data.message || '请求失败'))
        }else if(res.data.code === 302){
            ElMessage.error({
                message: res.data.message,
                offset: 100,
                duration: 5000
            })
            reject(new Error(res.data.message || '请求失败'))
        }else {
            // 处理其他状态码
            reject(new Error(res.data.message || '请求失败'))
        }
    })
})
// const baseURL = 'https://csindex.whsangbo.com/api/'
const baseURL = 'https://wjapi.surveydiscovery.com/api/'

const AxiosPost = (url,query) => {
    return axios.post(url,Qs.stringify(query))
}
export default AxiosPost;
